
# 数据库类
import pymysql
from setting import DB_INFO
from loguru import logger


class MysqlClient(object):

    # 初始化方法，建立连接
    def __init__(self):
        self.conn = pymysql.connect(**DB_INFO)  # 初始化数据库连接



    # 执行SQL语句的增删改
    def execute(self,sql):
        try:
            with self.conn.cursor() as cursor:
                cursor.execute(sql)
                self.conn.commit()
                logger.debug("执行的SQL:{}".format(sql))
        except Exception as e:
            logger.error("执行SQL错误:{},执行SQL:{}".format(e,sql))
            self.conn.rollback()



    # 执行查询
    def get_data(self,sql):
        try:
            with self.conn.cursor() as cursor:
                cursor.execute(sql)
                result = cursor.fetchall()
                return result
        except Exception as e:
            logger.error("执行SQL错误:{},执行SQL:{}".format(e, sql))

    # 关闭对象
    def close(self):
        self.conn.close()

